﻿Imports System.Data

''' <summary>
''' Codeplex Project: DvbViewer Signal Monitor
''' Mail: Andreas Poppe Entwickler
''' https://dvbviewersignalmonitor.codeplex.com
''' </summary>
''' <remarks></remarks>
Public Class Main_Form
    Const FormSize As Integer = 60
    Const TimerInterval = 1000
    Const MainFormText As String = "DvbViewer Signal Monitor "
    Private _dvb_DataTable As New DataTable("DVB_Data")
    Private Message_ComServer_Not_Avabile As Boolean = True
    Const HelpFile = "Setup_Infos.rtf"

    ''' <summary>
    ''' Event by Loading MainForm
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Main_Form_Load(sender As System.Object, e As System.EventArgs) Handles MyBase.Load
        setup_Mainform()
    End Sub

    ''' <summary>
    ''' setup Mainform by Start Program FormLoading 
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub setup_Mainform()
        Try
            showLocal_Time()
            Me.tsLabel1.Text = "Init"

            Me.FormBorderStyle = Windows.Forms.FormBorderStyle.Fixed3D
            create_DataTable_Colums()

            set_ToolTips()

            Me.Timer1.Interval = 1000 '/ 2
            Timer1.Start()
            Exit Sub
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error: Start " + MainFormText)
            Exit Sub
        End Try
    End Sub



    ''' <summary>
    '''  Set MainFormText with SystemTime
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub showLocal_Time()
        Try
            Me.Text = MainFormText.Trim & ": " & My.Computer.Clock.LocalTime
            Exit Sub
        Catch ex As Exception
            Me.Text = MainFormText
        End Try
    End Sub


    ''' <summary>
    ''' TimerEvent start Update Mainformprocess
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Timer1_Tick(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Timer1.Tick
        TimerEvent()
    End Sub

    ''' <summary>
    ''' udates Status COM-Server by Timer
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub TimerEvent()
        Try

            Dim height As Integer

            Dim get_Infos As New Get_DVB_Infos(_dvb_DataTable)

            showLocal_Time()

            If get_Infos.DVB_HardwareCount > 0 Then

                Me.tsLabel1.Text = get_Infos.DVB_Sender
                height = get_Infos.DVB_HardwareCount * 30 + 37
                Me.Height = height

                If Me.dgv.Visible = False Then
                    Me.dgv.Visible = True
                End If
            Else
                Me.tsLabel1.Text = "No active Software and Hardware found!"
                Me.dgv.Visible = False
                Me.Height = FormSize
            End If



            If get_Infos.HardWareOK Then
                Me.Timer1.Interval = TimerInterval / 2
            Else
                Me.Timer1.Interval = 10 * TimerInterval / 2
                If Message_ComServer_Not_Avabile Then
                    Message_ComServer_Not_Avabile = False
                    If get_Infos.ErrorMessage.Length > 0 Then
                        MessageBox.Show(get_Infos.ErrorMessage, "Error: Start DVBViewerServer", MessageBoxButtons.OK)
                        Help_With_F1()
                    End If
                End If

            End If
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error: TimerEvent " + MainFormText)
            Exit Sub
        End Try
    End Sub


    ''' <summary>
    ''' set one ToolTip Textin all DatagridviewHeaders
    ''' </summary>
    ''' <param name="mydgv"></param>
    ''' <param name="text"></param>
    ''' <remarks></remarks>
    Private Sub set_ToolTip_dgv_Header(mydgv As DataGridView, text As String)
        Try
            For Each Col As DataGridViewColumn In mydgv.Columns
                Col.ToolTipText = text
            Next
        Catch ex As Exception
            MessageBox.Show(ex.Message, "set_ToolTip_dgv_Header_dgv_Header: No ToolTips!", MessageBoxButtons.OK)
        End Try
    End Sub

    ''' <summary>
    ''' set ToolTips
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub set_ToolTips()
        ToolTip1.AutoPopDelay = 5000
        ToolTip1.InitialDelay = 1000
        ToolTip1.ReshowDelay = 500

        ' Force the ToolTip text to be displayed whether or not the form is active.
        ToolTip1.ShowAlways = True
        set_ToolTip_dgv_Header(Me.dgv, "Save Table with: Strg+S")
    End Sub

    ''' <summary>
    ''' create DataTable Colums and set Columns Width's
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub create_DataTable_Colums()

        _dvb_DataTable.Columns.Add("Device", Type.GetType("System.String"))
        _dvb_DataTable.Columns.Add("Signal-Quality", Type.GetType("System.Int32"))
        _dvb_DataTable.Columns.Add("Signal-Strength", Type.GetType("System.Int32"))
        _dvb_DataTable.Columns.Add("Signal-ErrorRate", Type.GetType("System.Int32"))

        Me.dgv.DataSource = _dvb_DataTable
        Me.dgv.Columns.Item(0).Width = 250
        Me.dgv.Columns.Item(1).Width = 90
        Me.dgv.Columns.Item(2).Width = 90
        Me.dgv.Columns.Item(3).Width = 90


        Me.dgv.Columns(0).SortMode = DataGridViewColumnSortMode.Automatic
        For i = 0 To Me.dgv.Rows.Count
            Me.dgv.Columns(1).SortMode = DataGridViewColumnSortMode.NotSortable
        Next


        For i = 1 To Me.dgv.ColumnCount - 1
            Me.dgv.Columns.Item(i).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
            Me.dgv.Columns.Item(i).DefaultCellStyle.Format = "#"
        Next

        dgv.RowHeadersVisible = False

        Dim width As Integer
        For i = 0 To Me.dgv.ColumnCount - 1
            width = width + Me.dgv.Columns.Item(i).Width
        Next


        Me.Width = width + 15
        Me.Height = FormSize


    End Sub


    ''' <summary>
    ''' MainForm HotKey's 
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub Main_Form_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles MyBase.KeyDown

        If (e.KeyCode = Keys.F1) Then
            Help_With_F1()
            Exit Sub
        End If

        If (e.Modifiers = Keys.Control And e.KeyCode = Keys.E) Then
            Copy_DataGridView_To_Clipboard(Me.dgv, True)
            Exit Sub
        End If
    End Sub


    ''' <summary>
    '''  Event Manager for F1 and Strg +S or Strg +X
    ''' </summary>
    ''' <param name="sender"></param>
    ''' <param name="e"></param>
    ''' <remarks></remarks>
    Private Sub dgv_KeyDown(sender As System.Object, e As System.Windows.Forms.KeyEventArgs) Handles dgv.KeyDown
        If (e.KeyCode = Keys.F1) Then
            Help_With_F1()
            Exit Sub
        End If


        If (e.Modifiers = Keys.Control And e.KeyCode = Keys.E) Then
            Copy_DataGridView_To_Clipboard(Me.dgv, True)
            Exit Sub
        End If

        If (e.Modifiers = Keys.Control And e.KeyCode = Keys.S) Then
            Export_dgv_as_CSV()
            Exit Sub
        End If

        If (e.Modifiers = Keys.Control And e.KeyCode = Keys.X) Then
            Export_dgv_as_Xml()
            Exit Sub
        End If

    End Sub

    ''' <summary>
    ''' get DirectoryName for FileSave Dialog's
    ''' </summary>
    ''' <param name="filepath"></param>
    ''' <returns></returns>
    ''' <remarks></remarks>
    Private Function get_DirectoryName(filepath As String) As String
        Try
            Return IO.Path.GetDirectoryName(filepath)
        Catch ex As Exception
            Return Environment.GetFolderPath(System.Environment.SpecialFolder.Personal)
        End Try
    End Function


    ''' <summary>
    ''' call HelpFile
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Help_With_F1()
        Dim App_Help As New get_Help(HelpFile)
    End Sub

    ''' <summary>
    ''' Save dgv as CSV-File
    ''' </summary>
    ''' <remarks></remarks>
    Private Sub Export_dgv_as_CSV()
        Dim saveFileDialog1 As New SaveFileDialog()
        saveFileDialog1.Filter = "csv-File|*.csv"
        saveFileDialog1.Title = "Save as Csv-File"
        saveFileDialog1.AddExtension = True
        saveFileDialog1.DefaultExt = "csv"
        saveFileDialog1.FileName = "Export.csv"
        saveFileDialog1.InitialDirectory = get_DirectoryName("")

        If (saveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            Dim export_csv As New Export_DGV_to_csv(Me.dgv, saveFileDialog1.FileName)
            If export_csv.Export_OK Then
                MessageBox.Show(" Export successful! ", "Export as Csv-File", MessageBoxButtons.OK)
            End If
        End If
    End Sub


    ''' <summary>
    ''' Save dgv as XML-File
    ''' </summary>
    Private Sub Export_dgv_as_Xml()
        Dim saveFileDialog1 As New SaveFileDialog()
        saveFileDialog1.Filter = "xml-File|*.xml"
        saveFileDialog1.Title = "Save as Xml-File"
        saveFileDialog1.AddExtension = True
        saveFileDialog1.DefaultExt = "xml"
        saveFileDialog1.FileName = "Export.xml"
        saveFileDialog1.InitialDirectory = get_DirectoryName("")

        If (saveFileDialog1.ShowDialog() = Windows.Forms.DialogResult.OK) Then
            Dim export_xml As New Export_Dgv_to_dgv_to_xml(Me.dgv, saveFileDialog1.FileName, Me.Text)
            If export_xml.Export_OK Then
                MessageBox.Show(" Export successful! ", "Export as Xml-File", MessageBoxButtons.OK)
            End If
        End If
    End Sub





    ''' <summary>
    ''' 
    ''' </summary>
    ''' <param name="dgv"></param>
    ''' <param name="withColumnHeader"></param>
    ''' <remarks></remarks>
    Private Sub Copy_DataGridView_To_Clipboard(ByRef dgv As DataGridView, Optional withColumnHeader As Boolean = True)
        Dim Clip_Board_Text As String = String.Empty

        Try

            'No empty Grid
            If dgv.ColumnCount > 0 Then

                Dim oCurrent_dgv_Col As DataGridViewColumn
                oCurrent_dgv_Col = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)

                'Get ColumnHeaders
                If withColumnHeader = True Then

                    Do
                        Clip_Board_Text = Clip_Board_Text & oCurrent_dgv_Col.HeaderText & Chr(Keys.Tab)
                        oCurrent_dgv_Col = dgv.Columns.GetNextColumn(oCurrent_dgv_Col, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
                    Loop Until oCurrent_dgv_Col Is Nothing

                    Clip_Board_Text = Clip_Board_Text.Substring(0, Clip_Board_Text.Length - 1)
                    Clip_Board_Text = Clip_Board_Text & Environment.NewLine
                End If

                'Get rows
                For Each row As DataGridViewRow In dgv.Rows
                    ' If Not row.IsNewRow Then

                    oCurrent_dgv_Col = dgv.Columns.GetFirstColumn(DataGridViewElementStates.Visible)

                    Do
                        If row.Cells(oCurrent_dgv_Col.Index).Value IsNot Nothing Then
                            Clip_Board_Text = Clip_Board_Text & row.Cells(oCurrent_dgv_Col.Index).Value.ToString
                        End If

                        Clip_Board_Text = Clip_Board_Text & Chr(Keys.Tab)
                        oCurrent_dgv_Col = dgv.Columns.GetNextColumn(oCurrent_dgv_Col, DataGridViewElementStates.Visible, DataGridViewElementStates.None)
                    Loop Until oCurrent_dgv_Col Is Nothing

                    Clip_Board_Text = Clip_Board_Text.Substring(0, Clip_Board_Text.Length - 1)
                    Clip_Board_Text = Clip_Board_Text & Environment.NewLine

                    'End If
                Next

                'last Line
                Clip_Board_Text = Clip_Board_Text & Me.Text & Chr(Keys.Tab) & tsLabel1.Text

                'Puting Text to clipboard
                If Clip_Board_Text.Length > 0 Then
                    Dim dataObj As New DataObject
                    dataObj.SetText(Clip_Board_Text)
                    Clipboard.SetDataObject(dataObj, True)
                End If

            End If

            Exit Sub
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error: Copy Text to ClipBoard", MessageBoxButtons.OK)
            Exit Sub
        End Try
    End Sub


End Class
